/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mytdev.commons.util;

import java.util.ArrayList;
import java.util.List;

/**
 * A composite filter that accept a value if all its underlying filters accept it.
 * @author Yann D'Isanto
 */
public class CompositeFilter<T> implements Filter<T> {

    private Mode mode;
    private List<Filter<T>> filters;

    public CompositeFilter() {
        this(null, Mode.AND);
    }

    public CompositeFilter(List<Filter<T>> filters) {
        this(filters, Mode.AND);
    }

    public CompositeFilter(List<Filter<T>> filters, Mode mode) {
        this.filters = filters == null
                ? new ArrayList<Filter<T>>()
                : new ArrayList<Filter<T>>(filters);
        this.mode = mode;
    }

    /**
     * Adds the specified filter.
     * @param filter a filter.
     */
    public void addFilter(Filter<T> filter) {
        filters.add(filter);
    }

    /**
     * Removes the specified filter.
     * @param filter a filter
     */
    public void removeFilter(Filter<T> filter) {
        filters.remove(filter);
    }

    public Mode getMode() {
        return mode;
    }

    public void setMode(Mode mode) {
        this.mode = mode;
    }

    @Override
    public boolean accept(T t) {
        switch (mode) {
            case AND:
                for (Filter<T> filter : filters) {
                    if (!filter.accept(t)) {
                        return false;
                    }
                }
                return true;
            case OR:
                for (Filter<T> filter : filters) {
                    if (filter.accept(t)) {
                        return true;
                    }
                }
                break;
        }
        return false;
    }

    public enum Mode {

        AND,
        OR
    }
}
